
import java.io.*;
import java.util.*;

/*
 * The StartRemotePeers class begins remote peer processes. 
 * It reads configuration file PeerInfo.cfg and starts remote peer processes.
 */

public class StartRemotePeers {

	public Vector<PeerInfo> peerInfoVector;
	
	public void getConfiguration()
	{
		String st;
		
		peerInfoVector = new Vector<PeerInfo>();
		try {
			BufferedReader in = new BufferedReader(new FileReader("PeerInfo.cfg"));
			while((st = in.readLine()) != null) {
				
				 String[] tokens = st.split("\\s+");
			    
			     peerInfoVector.addElement(new PeerInfo(tokens[0], tokens[1], tokens[2]));
			
			}
			
			in.close();
		}
		catch (Exception e) {
			System.out.println(e.toString());
		}
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		try {
			StartRemotePeers myStart = new StartRemotePeers();
			myStart.getConfiguration();
			Process[] processArray = new Process[myStart.peerInfoVector.size()];
		
			// get current path
			String path = System.getProperty("user.dir");
			
			// start clients at remote hosts
			for (int i = 0; i < myStart.peerInfoVector.size(); i++) {
				PeerInfo pInfo = (PeerInfo) myStart.peerInfoVector.elementAt(i);
				
				System.out.println("Start remote peer " + pInfo.getPeerID() +  " at " + pInfo.getHostname() );
				
				processArray[i] = Runtime.getRuntime().exec("ssh " + pInfo.getHostname() + " cd " + path + "; java PeerProcess " + pInfo.getPeerID());

				Thread.sleep(3000);
			}
			
			System.out.println("Starting all remote peers has done." );

			/*while(PeerProcess.hasEnded == false);

			for(int i=0; i < processArray.length; i++)
				processArray[i].waitFor();

			System.out.println("All peers completed download");*/
		}
		catch (Exception e) {
			System.out.println(e);
			e.printStackTrace();
		}
	}

}

